package Presenter;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import Models.POLines;

public class POLinesPresenter extends AbstractPresenter<POLines> {
	final String SINGLEITEM = "poLines";
	final String MULTIITEM = "pOLiness";
	
	public ArrayList<POLines> tryJSONParseArray(String input){
		return super.doJSONParseArray(input, SINGLEITEM, MULTIITEM);
	}
	
	public POLines tryJSONParse(String input){
		return super.doJSONParse(input, SINGLEITEM);
	}
	
	public POLines createItemFromJSONObject(JSONObject jsonObject){
		POLines item = new POLines();
		try{
			item.setContract(jsonObject.getBoolean("POLContract"));
			item.setDesc(jsonObject.getString("description"));
			item.setPoLineCost(jsonObject.getDouble("POLCost"));
			item.setPoLineID(jsonObject.getInt("polid"));
			
			final StockCodePresenter presenter = new StockCodePresenter();
			JSONObject jsonSC = jsonObject.getJSONObject("polpn");
			item.setPoLinePartNumber(presenter.createItemFromJSONObject(jsonSC));
			
			item.setPoLineQtyReceived(jsonObject.getInt("pOLQtyRcvd"));
			item.setPoLineQuantity(jsonObject.getInt("POLQty"));
			item.setPoLineReceived(jsonObject.getBoolean("POLRcvd"));
			
			return item;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(POLines item){
		try{
			JSONObject json = new JSONObject();
			json.put("POLContract", item.isContract());
			json.put("description", item.getDesc());
			json.put("POLCost", item.getPoLineCost());
			json.put("polid", item.getPoLineID());
			json.put("pOLQtyRcvd", item.getPoLineQtyReceived());
			json.put("POLQty", item.getPoLineQuantity());
			json.put("POLRcvd", item.isPoLineReceived());
			
			if(item.getPoLinePartNumber()!=null){
				final StockCodePresenter presenter = new StockCodePresenter();
				json.put("polpn", presenter.createJSON(item.getPoLinePartNumber()));
			} else {
				json.put("polpn", JSONObject.NULL);
			}

			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public POLines getEmptyEntity(){
		POLines entity = new POLines();
		return entity;
	}
}
